package com.acxiom.bsh.taobao.sdk;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.acxiom.bsh.logger.LoggerManager;
import com.alibaba.appengine.jae.model.TaobaoTinyUser;
import com.alibaba.fastjson.JSON;
import com.taobao.api.internal.util.WebUtils;

/**
 * 
 * @Description: TOP User Authorized
 * @author jerche
 * @updateUser
 * @updateDate
 */
@Component
public class TbAuthorize {
	/**
	 * 日志对象
	 */

	private static String AUTHORIZE_URL = "https://oauth.taobao.com/authorize";
	private static String AUTHORIZE_SANDBOX_URL = "https://oauth.tbsandbox.com/authorize";
	private static String TOKEN_URL = "https://oauth.taobao.com/token";
	private static String TOKEN_SANDBOX_URL = "https://oauth.tbsandbox.com/token";
	private static String LOGOFF_URL = "https://oauth.taobao.com/logoff";
	private static String LOGOFF_SANDBOX_URL = "https://oauth.tbsandbox.com/logoff";

	private static String VIEW_WEB = "web";
	private static String VIEW_TMALL = "tmall";
	private static String VIEW_WAP = "wap";

	@Value("${ewsDomain}")
	private String ewsDomain;

	@Value("${ewsAppKey}")
	private String ewsAppKey;

	@Value("${ewsAppSecret}")
	private String ewsAppSecret;

	@Value("${ewsSessionKey}")
	private String topSessionKey;

	@Value("${topServiceUrl}")
	private String topServiceUrl;

	public static final String ACCESS_TOKEN = "ACCESS_TOKEN";

	/**
	 * 构造授权url
	 * 
	 * @param clientId
	 * @param redirectUri
	 * @param state
	 * @return
	 */
	public static String buildAuthorizeUrl(String clientId, String redirectUri, String state) {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
		HttpServletRequest request = sra.getRequest();
		String user_agent = request.getHeader("user-agent");
		Boolean isMobile = isMobileDevice(user_agent);
		StringBuffer sb = new StringBuffer(AUTHORIZE_URL);
		sb.append("?client_id=" + clientId);
		sb.append("&response_type=code");
		sb.append("&redirect_uri=" + redirectUri);
		sb.append("&state=" + state);
		sb.append("&view=" + (isMobile ? VIEW_WAP : VIEW_WEB));
		return sb.toString();
	}

	/**
	 * 构造获取access_token Url
	 * 
	 * @param clientId
	 * @param clientSecret
	 * @param code
	 * @param redirectUri
	 * @param state
	 * @return
	 */
	public static String buildTokenUrl(String clientId, String clientSecret, String code, String redirectUri, String state) {
		StringBuffer sb = new StringBuffer(TOKEN_URL);
		sb.append("?client_id=" + clientId);
		sb.append("&client_secret=" + clientSecret);
		sb.append("&grant_type=grant_type");
		sb.append("&code=" + code);
		sb.append("&redirect_uri=" + redirectUri);
		sb.append("&state=" + state);
		sb.append("&view=" + VIEW_WAP);
		return sb.toString();
	}

	/**
	 * 获取token
	 * 
	 * @param clientId
	 * @param clientSecret
	 * @param code
	 * @param redirectUri
	 * @param state
	 * @return
	 */
	public static String getToken(String clientId, String clientSecret, String code, String redirectUri, String state) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("client_id", clientId);
		params.put("client_secret", clientSecret);
		params.put("grant_type", "authorization_code");
		params.put("code", code);
		params.put("redirect_uri", redirectUri);
		params.put("state", state);
		params.put("view", VIEW_WAP);
		String res = "";
		try {
			WebUtils.setIgnoreSSLCheck(true);
			res = WebUtils.doPost(TOKEN_URL, params, 30000, 30000);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return res;
	}

	/**
	 * 刷新token
	 * 
	 * @param token
	 * @param clientId
	 * @param clientSecret
	 */
	public static void refreshToken(String token, String clientId, String clientSecret) {
		Map<String, String> props = new HashMap<String, String>();
		props.put("grant_type", "refresh_token");
		props.put("refresh_token", token);
		props.put("client_id", clientId);
		props.put("client_secret", clientSecret);
		String s = "";
		try {
			WebUtils.setIgnoreSSLCheck(true);
			s = WebUtils.doPost(TOKEN_URL, props, 30000, 30000);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取登录用户昵称
	 * 
	 * @param session
	 * @return
	 */
	public static TaobaoTinyUser getUser(HttpSession session) {
		TaobaoTinyUser taobaoTinyUser = (TaobaoTinyUser) session.getAttribute(TaobaoTinyUser.SESSION_KEY);
		return taobaoTinyUser;
	}

	/**
	 * 获取access token
	 * 
	 * @param session
	 * @return
	 */
	public static String getAccessToken(HttpSession session) {
		return (String) session.getAttribute(ACCESS_TOKEN);
	}

	/**
	 * android : 所有android设备 mac os : iphone ipad windows phone:Nokia等windows系统的手机
	 */
	public static boolean isMobileDevice(String requestHeader) {
		String[] deviceArray = new String[] { "iphone", "android", "ipad", "phone", "mobile", "windows phone" };
		if (requestHeader == null)
			return false;
		requestHeader = requestHeader.toLowerCase();
		for (int i = 0; i < deviceArray.length; i++) {
			if (requestHeader.indexOf(deviceArray[i]) > 0) {
				return true;
			}
		}
		return false;
	}

	public String getTaoBaoId(String code) {

		String URL = "curl -d " + "grant_type=authorization_code&grant_type=authorization_code&client_id=" + ewsAppKey + "&client_secret=" + ewsAppSecret + "&redirect_uri=https://siemens.ews.m.jaeapp.com/" + System.currentTimeMillis() + "&code=" + code + " " + "https://oauth.taobao.com/token";
		InputStream in = null;
		try {
			Process pro = Runtime.getRuntime().exec(URL);
			pro.waitFor();
			in = pro.getInputStream();
			BufferedReader read = new BufferedReader(new InputStreamReader(in));
			StringBuffer resultBuffer = new StringBuffer();
			while (read.ready()) {
				resultBuffer.append(read.readLine());
			}
			Object obj = JSON.parseObject(resultBuffer.toString()).get("taobao_user_nick");
			if (obj != null) {
				return obj.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}
}
